package com.virus.mall.controller.mall;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.virus.mall.model.Result;
import com.virus.mall.model.User;
import com.virus.mall.model.bo.UpdateUserDataBo;
import com.virus.mall.model.bo.UserLoginBo;
import com.virus.mall.model.bo.UserLogoutClientBo;
import com.virus.mall.model.bo.UserSignUpBo;
import com.virus.mall.model.UserUpdatePwd;
import com.virus.mall.model.vo.UserLoginVo;
import com.virus.mall.model.vo.UserSignUpVo;
import com.virus.mall.service.UserService;
import com.virus.mall.service.impl.UserServiceImpl;
import com.virus.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Classname MallUserServlet
 * @Description NULL
 * @Date 2021/4/20 14:24
 * @Created by virus
 */
@WebServlet("/api/mall/user/*")
public class MallUserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/mall/user/", "");
        if (op.equals("signup")) {
            signup(request, response);
        } else if (op.equals("login")) {
            login(request, response);
        } else if (op.equals("logoutClient")) {
            logoutClient(request, response);
        } else if (op.equals("updatePwd")) {
            updatePwd(request, response);
        } else if (op.equals("updateUserData")) {
            updateUserData(request, response);
        }
    }

    /**
     * 注册
     * @param request
     * @param response
     * @throws IOException
     */
    private void signup(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        UserSignUpBo userSignUpBo = objectMapper.readValue(requestBody, UserSignUpBo.class);
        UserSignUpVo userSignUpVo = null;
        try {
            userSignUpVo = userService.signup(userSignUpBo);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("注册未成功，可能存在相同的用户名或昵称")));
            return;
        }
        if (userSignUpVo == null) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("注册返回未成功，可能存在相同的用户名或昵称")));
            return;
        }
        HttpSession session = request.getSession();
        session.setAttribute("email", userSignUpVo.getToken());
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(userSignUpVo)));
    }

    /**
     * 登录
     * @param request
     * @param response
     * @throws IOException
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        UserLoginBo userLoginBo = objectMapper.readValue(requestBody, UserLoginBo.class);
        Integer code = userService.login(userLoginBo);
        if (code == 404) {
            response.setStatus(code);
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("登录失败")));
            return;
        }
        UserLoginVo userLoginVo = new UserLoginVo(userLoginBo.getEmail(), userLoginBo.getEmail());
        HttpSession session = request.getSession();
        session.setAttribute("email", userLoginVo.getToken());
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(userLoginVo)));
    }

    /**
     * 登出用户
     * @param request
     * @param response
     * @throws IOException
     */
    private void logoutClient(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        UserLogoutClientBo userLogoutClientBo = objectMapper.readValue(requestBody, UserLogoutClientBo.class);
        if (userLogoutClientBo.getToken() == null) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("登出错误")));
            return;
        }
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
    }

    /**
     * 更新用户密码
     * @param request
     * @param response
     * @throws IOException
     */
    private void updatePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        UserUpdatePwd userUpdatePwd = objectMapper.readValue(requestBody, UserUpdatePwd.class);
        boolean result = userService.updatePwd(userUpdatePwd);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
            return;
        }
        response.getWriter().println(objectMapper.writeValueAsString(Result.error("更新密码失败")));
    }

    /**
     * 更新用户信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void updateUserData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        UpdateUserDataBo updateUserDataBo = null;
        try {
            updateUserDataBo = objectMapper.readValue(requestBody, UpdateUserDataBo.class);
        } catch (Exception e){
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("传入参数错误")));
            return;
        }
        boolean result;
        try {
            result = userService.updateUserData(updateUserDataBo);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("修改用户信息出现错误，可能存在相同的用户名和昵称")));
            return;
        }
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
            return;
        }
        response.getWriter().println(objectMapper.writeValueAsString(Result.error("更新用户信息失败")));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/mall/user/", "");
        if (op.startsWith("data")) {
            data(request, response);
        }
    }

    /**
     * 获取用户数据
     * @param request
     * @param response
     * @throws IOException
     */
    private void data(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = request.getParameter("token");
        User user = userService.data(token);
        if (user == null) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("数据传输错误")));
            return;
        }
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(user)));
    }
}
